<template>
  <div class="app-container">
    <v-row :gutter="24">
      <v-col>
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="参数名称"
                v-model="queryParams.configName"
                placeholder="请输入参数名称"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="参数键名"
                v-model="queryParams.configKey"
                placeholder="请输入参数键名"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="系统内置"
                v-model="queryParams.configType"
                :items="typeOptions"
                item-text="dictLabel"
                item-value="dictValue"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 2px;max-width: 180px">
              <v-menu
                ref="dateRangeMenu"
                v-model="dateRangeMenu"
                :close-on-content-click="false"
                transition="scale-transition"
                offset-y
                max-width="240px"
                min-width="auto"
                style="width: 240px;padding-top: 0;margin-top: 0"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="date"
                    label="创建时间"
                    prepend-icon="mdi-calendar"
                    v-bind="attrs"
                    v-on="on"
                    clearable
                    style="width: 240px;padding-top: 0"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="date"
                  no-title
                  @input="dateRangeMenu = false"
                  style="padding: 0"
                ></v-date-picker>
              </v-menu>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>

        <!-- 表格操作按钮区 -->
        <v-row style="margin-bottom: -5px">
          <v-col md="1" style="max-width: 84px">
            <v-btn
              color="primary"
              plain
              small
              outlined
              @click="handleAdd"
              v-hasPermi="['system:config:add']">
              <v-icon left>
                mdi-plus
              </v-icon>
              新增
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small
              plain
              outlined
              :disabled="single"
              @click="handleUpdate(ids[0])"
              v-hasPermi="['system:config:edit']">
              <v-icon left>
                mdi-pencil
              </v-icon>
              修改
            </v-btn>
          </v-col>
          <!--todo 二次确认删除按钮 -->
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small color="error"
              plain
              outlined
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:config:remove']">
              <v-icon left>
                mdi-delete
              </v-icon>
              删除
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small
              plain
              outlined
              @click="handleExport"
              v-hasPermi="['system:config:export']">
              <v-icon left>
                mdi-upload
              </v-icon>
              导出
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              type="text" color="error"
              small
              plain
              outlined
              @click="handleClearCache"
              v-hasPermi="['system:config:remowe']">
              <v-icon left>
                mdi-autorenew
              </v-icon>
              清理缓存
            </v-btn>
          </v-col>
          <v-col style="float: right">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </v-col>
        </v-row>
      </v-col>
    </v-row>

    <!-- 表格-->
    <v-main>
      <v-data-table v-if="configList"
                    v-model="ids"
                    :headers="headers"
                    :items="configList"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="configId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >

        <template v-slot:item.configName="{ item }">
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <div class="omitted" v-bind="attrs" v-on="on">{{ item.configName }}</div>
            </template>
            <span>{{ item.configName }}</span>
          </v-tooltip>
        </template>

        <template v-slot:item.configKey="{ item }">
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <div class="omitted" v-bind="attrs" v-on="on">{{ item.configKey }}</div>
            </template>
            <span>{{ item.configKey }}</span>
          </v-tooltip>
        </template>

        <template v-slot:item.configValue="{ item }">
          <div class="omitted">{{ item.configValue }}</div>
        </template>

        <template v-slot:item.remark="{ item }">
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <div class="omitted" v-bind="attrs" v-on="on">{{ item.remark }}</div>
            </template>
            <span>{{ item.remark }}</span>
          </v-tooltip>
        </template>

        <!-- 系统内置 -->
        <template v-slot:item.configType="{ item }">
          {{ typeFormat(item) }}
        </template>

        <!-- test -->
        <template v-slot:item.createTime="{ item }">
          <v-hover v-slot="{ hover }">
            <v-card
              :elevation="hover ? 12 : 2"
              color="grey lighten-4"
              style="border: none !important;background-color: transparent;max-height: 44px;width: 156px"
            >
              <div
                v-if="hover"
                style="height: 100%;background-color: transparent;max-height: 44px;overflow: auto"
              >
                <v-btn text
                       small
                       plain
                       height="20"
                       width="40"
                       @click="handleUpdate(item)"
                       v-hasPermi="['system:user:edit']">
                  <v-icon small>
                    mdi-pencil
                  </v-icon>
                  修改
                </v-btn>
                <span v-if="item && item.showConfirmDelete">
                  <v-tooltip top>
                    <template v-slot:activator="{ on, attrs }">
                      <v-btn
                        small color="error"
                        plain
                        height="20"
                        width="40"
                        v-bind="attrs"
                        v-on="on"
                        @click="handleDelete(item)"
                        v-hasPermi="['system:user:remove']">
                        <v-icon small>
                          mdi-delete
                        </v-icon>
                        确定
                      </v-btn>
                    </template>
                    <span>请再次点击确定删除</span>
                  </v-tooltip>
                </span>
                <span v-if="item && !item.showConfirmDelete">
                  <v-btn color="#C62828"
                         small
                         plain
                         height="20"
                         width="40"
                         @click="onClickDelete(item)">
                    <v-icon small>
                      mdi-delete
                    </v-icon>
                    删除
                  </v-btn>
                </span>
              </div>
              <div
                v-if="!hover"
                style="height: 100%;"
              >
                {{ item.createTime }}
              </div>
            </v-card>
          </v-hover>
        </template>

        <!-- 按钮插槽 -->
        <!--<template v-slot:item.actions="{ item }">-->
        <!--  <v-btn text-->
        <!--         small-->
        <!--         plain-->
        <!--         height="20"-->
        <!--         width="40"-->
        <!--         @click="handleUpdate(item)"-->
        <!--         v-hasPermi="['system:user:edit']">-->
        <!--    <v-icon small>-->
        <!--      mdi-pencil-->
        <!--    </v-icon>-->
        <!--    修改-->
        <!--  </v-btn>-->
        <!--  &lt;!&ndash; 删除确认 &ndash;&gt;-->
        <!--  <span v-if="item && item.showConfirmDelete">-->
        <!--    <v-tooltip top>-->
        <!--      <template v-slot:activator="{ on, attrs }">-->
        <!--        <v-btn-->
        <!--          small color="error"-->
        <!--          plain-->
        <!--          height="20"-->
        <!--          width="40"-->
        <!--          v-bind="attrs"-->
        <!--          v-on="on"-->
        <!--          @click="handleDelete(item)"-->
        <!--          v-hasPermi="['system:user:remove']">-->
        <!--          <v-icon small>-->
        <!--            mdi-delete-->
        <!--          </v-icon>-->
        <!--          确定-->
        <!--        </v-btn>-->
        <!--      </template>-->
        <!--      <span>请再次点击确定删除</span>-->
        <!--    </v-tooltip>-->
        <!--  </span>-->
        <!--  <span v-if="item && !item.showConfirmDelete">-->
        <!--    <v-btn color="#C62828"-->
        <!--           small-->
        <!--           plain-->
        <!--           height="20"-->
        <!--           width="40"-->
        <!--           @click="onClickDelete(item)">-->
        <!--      <v-icon small>-->
        <!--        mdi-delete-->
        <!--      </v-icon>-->
        <!--      删除-->
        <!--    </v-btn>-->
        <!--  </span>-->
        <!--</template>-->
      </v-data-table>

      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <!-- 编辑对话框 -->
    <v-dialog
      v-model="visible"
      persistent
      max-width="500px">

      <v-card>
        <!-- 对话框标题 -->
        <v-card-title>
          <span style="font-size: 18px">{{ title }}</span>
        </v-card-title>

        <!-- 表单 -->
        <v-form ref="form" v-model="valid">
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="12">
                  <v-text-field
                    label="*参数名称"
                    v-model="form.configName"
                    :rules="rules.configName"
                    placeholder="请输入参数名称"
                    required
                    autofocus
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="12">
                  <v-text-field
                    label="*参数键名"
                    v-model="form.configKey"
                    :rules="rules.configKey"
                    placeholder="请输入参数键名"
                    required
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="12">
                  <v-text-field
                    label="*参数键值"
                    v-model="form.configValue"
                    :rules="rules.configValue"
                    placeholder="请输入参数键值"
                    required
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="12">
                  <v-radio-group
                    label="系统内置"
                    v-model="form.configType"
                    row dense style="margin: 0;"
                  >
                    <v-radio
                      v-for="dict in typeOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></v-radio>
                  </v-radio-group>
                </v-col>
                <v-col cols="12" sm="12" style="padding-bottom: 0;padding-top: 0">
                  <v-textarea
                    v-model="form.remark"
                    label="备注"
                    placeholder="请输入内容"
                    auto-grow
                    filled
                    clearable
                    dense
                  >
                  </v-textarea>
                </v-col>
              </v-row>
            </v-container>
            <small class="ml10">*表示必需字段</small>
          </v-card-text>
        </v-form>

        <!-- 底部操作按钮 -->
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="updateVisible(false)">
            取消
          </v-btn>
          <v-btn
            color="blue darken-1"
            text
            @click="submitForm">
            保存
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig, clearCache } from "@/api/system/config";

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalPages: 0, // 总页数
        configName: undefined,
        configKey: undefined,
        configType: undefined
      },
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      headers: [
        { text: '参数主键', value: 'configId',  align: 'center', sortable: false },
        { text: '参数名称', value: 'configName', align: 'center', sortable: false },
        { text: '参数键名', value: 'configKey', align: 'center', sortable: false },
        { text: '参数键值', value: 'configValue', align: 'center', sortable: false},
        { text: '系统内置', value: 'configType', sortable: false, align: 'center' },
        { text: '备注', value: 'remark', sortable: false, align: 'center' },
        { text: '创建时间', value: 'createTime', sortable: false, align: 'center', width: '170' },
        //{ text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      columns: [],
      // 表单参数
      form: {},
      dateRangeMenu: false,
      date: null,
      valid: false,
      visible: false, // 是否显示对话框
      // 表单校验
      rules: {
        configName: [
          val => (val || '').length > 0 || '参数名称不能为空'
        ],
        configKey: [
          val => (val || '').length > 0 || '参数键名不能为空'
        ],
        configValue: [
          val => (val || '').length > 0 || '参数键值不能为空'
        ]
      }
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      listConfig(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.configList = response.rows;
          this.total = response.total;
          // 总页数
          this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
          this.loading = false;
        }
      );
    },
    // 参数系统内置字典翻译
    typeFormat(row) {
      return this.selectDictLabel(this.typeOptions, row.configType);
    },
    // 表单重置
    reset() {
      this.form = {
        configType: "Y",
      };
      if (this.$refs.form) {
        this.$refs.form.reset(); // 重置
        this.$refs.form.resetValidation();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.dateRange = [];
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加参数";
      this.visible = true;
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId || this.ids
      getConfig(configId).then(response => {
        this.form = response.data;
        this.title = "修改参数";
        this.visible = true;
      });
    },
    validate () {
      this.$refs.form.validate();
    },
    /** 提交按钮 */
    async submitForm() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await this.validate();
      if (this.valid) {
        if (this.form.configId != undefined) {
          updateConfig(this.form).then(response => {
            this.$store.dispatch('snackbar/openSnackbar',{ msg: '修改成功', color: 'success' })
            this.getList();
            this.visible = false;

          });
        } else {
          addConfig(this.form).then(response => {
            this.$store.dispatch('snackbar/openSnackbar',{ msg: '新增成功',color: 'success' })
            this.getList();
            this.visible = false;
          });
        }
      }
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const configIds = row.configId || this.ids.map(item => item.configId);
      await delConfig(configIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', { msg: '删除成功',color: 'success' })
          this.getList();
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 清理缓存按钮操作 */
    handleClearCache() {
      clearCache().then(response => {
        this.msgSuccess("清理成功");
      });
    },
    updateVisible(value) {
      this.reset();
      this.visible = value;
    },
  }
};
</script>
